package ganga.custodian.sensors;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import java.util.Random;

/**
 * Сервис генератора сердечного ритма
 * @author Apocrypha 22.06
 */
public class HeartBeatService extends Service {
	public static class Timekeeper {
		private int median;
		private int variance;
		private Random noise;
		Generator generator;
		private Thread timerThread;
		private Runnable doBeat;

		/**
		 * Хронометрист. Вызывает генератор с указанной периодичностью
		 * @param median медиана
		 * @param variance вариация
		 * @param generator кого вызывать
		 */
		public Timekeeper(int median, int variance, Generator generator) {
			this.median = median;
			this.variance = variance;
			noise = new Random();

			this.generator = generator;

			setDoBeat();
			timerThread = new Thread(doBeat, "HeartBeat timekeeper thread");
		}
		long currentValue(){
			return System.currentTimeMillis();
		}

		public Runnable getDoBeat() {
			return doBeat;
		}

		public void setDoBeat() {
			this.doBeat = new Runnable() {
				@Override
				public void run() {
					for(;;){//for ever
						long timeToNextEvent = getNextEventDelay();
						try {
							generator.doWork(currentValue());
							Thread.sleep(timeToNextEvent);
						} catch (InterruptedException e) {
							// Sombody want to stop timer
							e.printStackTrace();
						}
					}
				}//run
			};
		}

		public int getNoise() {
			return noise.nextInt(variance) - variance;
		}

		public int getVariance() {
			return variance;
		}

		public void setVariance(int variance) {
			this.variance = variance;
		}

		public int getMedian() {
			return median;
		}

		public void setMedian(int median) {
			this.median = median;
		}
		/**
         * @return  Через сколько милисекунд произойдёт следующее событие
         * вернее, насколько оно откладывается
		 */
		private long getNextEventDelay() {
			long result;
			
			int deviation = calculateDeviation();
			result = median + deviation; 
			
			return result;
		}

		private int calculateDeviation() {
			int deviation = getNoise();
			return deviation;
		}

		public void startTimer() {
			timerThread.start();
		}
		public void stopTimer(){
			try {
				timerThread.interrupt();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}//
	public class Generator{
		public static final String GENERATOR_DOWORK = "Generator make some work"; 
		public void doWork(long timeStamp){
			Intent intent = new Intent("ganga.custodian.sensors.SensorsMonitor");
			intent.putExtra("Description", "Heart beat");
			intent.putExtra("TimeStamp", timeStamp);
			startService(intent);
		}
	}
	protected Generator generator;
	protected Timekeeper timekeeper; 

	@Override
	public void onCreate() {
		generator = new Generator();
		timekeeper = new Timekeeper(900, 200, generator);
		timekeeper.startTimer();
	}
	@Override
	public IBinder onBind(Intent intent) {
		// No need to implement
		return null;
	}
	public void onDestroy(){
		//TODO: Stop generator
		super.onDestroy();
	}
}